/**
 * 
 */
package org.libermundi.theorcs.chronicles.dao.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.libermundi.theorcs.chronicles.dao.InternalEmailDao;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.model.message.TargetRole;
import org.libermundi.theorcs.chronicles.model.message.impl.InternalEmail;
import org.libermundi.theorcs.core.dao.exception.OrcsDataAccessException;
import org.libermundi.theorcs.core.dao.hibernate.HibernateGenericDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 * @author Izo
 *
 */
@Repository
public class InternalEmailDaoImpl extends HibernateGenericDao<InternalEmail, Long> implements InternalEmailDao {

	private static final Logger logger = LoggerFactory.getLogger(InternalEmailDaoImpl.class); 

	public InternalEmailDaoImpl(){
		super();
		_mappedClazz = InternalEmail.class;
	}

	/* (non-Javadoc)
	 * @see org.libermundi.theorcs.chronicles.dao.MessageDao#getPersonaChronicleMessages(org.libermundi.theorcs.chronicles.model.Persona)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<InternalEmail> getPersonaMessages(Persona persona) {
		List<InternalEmail> result;
		try{
			result = createQuery("SELECT message " +
					"FROM InternalEmailTarget as target INNER JOIN target.internalEmail as message INNER JOIN target.persona as perso" +
				" where perso = :perso " +
				" and target.role <> :role" + 
				" order by message.id")
				.setParameter("perso", persona)
				.setParameter("role", TargetRole.BY)
				.list();
		} catch (HibernateException e) {
			logger.error("Exception in getPersonaMessages(" + persona +")", e);
			throw new OrcsDataAccessException("Exception in getPersonaMessages : " + persona, e);
		}
		return result;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.libermundi.theorcs.chronicles.dao.InternalEmailDao#getPersonaSentMessages(org.libermundi.theorcs.chronicles.model.Persona)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<InternalEmail> getPersonaSentMessages(Persona persona) {
		List<InternalEmail> result;
		try{
			result = createQuery("Select message " +
					"FROM InternalEmailTarget as target INNER JOIN target.internalEmail as message INNER JOIN target.persona as perso" +
					" where perso = :perso " +
					" and target.role = :role" + 
					" order by message.id")
					.setParameter("perso", persona)
					.setParameter("role", TargetRole.BY)
					.list();
		} catch (HibernateException e) {
			logger.error("Exception in getPersonaMessages(" + persona +")", e);
			throw new OrcsDataAccessException("Exception in getPersonaMessages : " + persona, e);
		}
		return result;
	}
}
